package ntd.util.frame.storage.context;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import ntd.util.frame.storage.NtdStorage;
import ntd.util.frame.storage.bo.StorageConfig;
import ntd.util.frame.storage.bo.StorageInBO;
import ntd.util.frame.storage.factory.FactoryStorage;
import ntd.util.modular.function.entity.ChannelBusiness;
import ntd.util.modular.function.util.UtilChannelBusiness;
import org.springframework.web.multipart.MultipartFile;

@Data
public class StorageContext {

    private String newFileName;

    private StorageInBO storageInBO;

    private NtdStorage ntdStorage;

    public static StorageContext init(StorageInBO storage) {
        StorageContext storageContext = new StorageContext();
        storageContext.setStorageInBO(storage);
        storageContext.setNewFileName(generateKey(storage.getOriginName(), storage.getFileKey()));
        storageContext.setNtdStorage(initNtdStorage(storage.getChannelBusinessId()));
        return storageContext;
    }

    private static NtdStorage initNtdStorage(String channelBusinessId) {
        ChannelBusiness channelBusiness = UtilChannelBusiness.getById(channelBusinessId);
        return FactoryStorage.generatorStorage(channelBusiness.getEnumPlatformType(), StorageConfig.transform(channelBusiness));
    }

    private static String generateKey(String originalFilename, String fileKey) {
        if (StrUtil.isBlank(fileKey) || "undefined".equals(fileKey)) {
            fileKey = RandomUtil.randomString(20);
        }
        return StrUtil.concat(true, fileKey, ".", FileUtil.getSuffix(originalFilename));
    }
}
